import React, { useState, useImperativeHandle } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';

// 规定图片的格式及大小
const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传JPG/PNG格式的图片');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片的大小不能超过2MB!');
  }
  return isJpgOrPng && isLt2M;
};

type Iprops = {
  imageUrl: string;
  setImageUrl: (imageUrl: string) => void;
};

const MyUpload: React.FC<Iprops> = (props) => {
  const [loading, setLoading] = useState(false);

  let { imageUrl, setImageUrl } = props;
  //
  const handleChange = (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // console.log(info)
      // Get this url from response in real world.
      setLoading(false);
      setImageUrl(info.file.response.imgUrl);

      message.open({
        type: 'success',
        content: '上传成功',
      });
    }

    if (info.file.status === 'error') {
      setLoading(false);
      message.open({
        type: 'error',
        content: '上传失败',
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  // https://chst.vip/images/img-1673438800543.png
  //https://chst.vip/images/img-1673438741995.png

  // https://chst.vip/images/img-1673438948318.png
  // https://chst.vip/images/img-1673438948318.png

  //https://chst.vip/images/img-1673439151458.png
  // ttps://chst.vip/images/img-1673439180468.png

  return (
    <Upload
      name="img"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action="/api/upload/uploadImg"
      method="post"
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {imageUrl ? (
        <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
      ) : (
        uploadButton
      )}
    </Upload>
  );
};

export default MyUpload;
